﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Publishing.WebControls;

namespace MultiLevelSelectField
{
    /// <summary>
    /// This class is the editor for the MultiLevelSelectField
    /// </summary>
    public class MultiLevelSelectFieldEditor : UserControl, IFieldEditor
    {
        private SPField Field { get; set; }

        /// <summary>
        /// A reference to the Textbox-url
        /// </summary>
        protected AssetUrlSelector ausList;

        #region IFieldEditor Members
        public bool DisplayAsNewSection
        {
            get 
            { 
                return true; 
            }
        }

        public void InitializeWithField(SPField field)
        {
            Field = field;
        }

        protected override void CreateChildControls()
        {
            if (Field != null)            
            {
                // An existing field/column is being edited.
                // Get the field and the values.
                MultiLevelSelectField f = (MultiLevelSelectField)Field;
                ausList.AssetUrl = f.ListUrl;
            }

            base.CreateChildControls();
        }

        /// <summary>
        /// Set properties on field
        /// </summary>
        /// <param name="field"></param>
        /// <param name="isNewField"></param>
        public void OnSaveChange(SPField field, bool isNewField)
        {
            MultiLevelSelectField f = (MultiLevelSelectField)field;
            try
            {
                using (SPWeb web = SPContext.Current.Site.OpenWeb(ausList.AssetUrl))
                {
                    SPList list = web.GetList(ausList.AssetUrl);
                    f.ListUrl = list.RootFolder.ServerRelativeUrl;
                }
            }
            catch (Exception ie)
            {
                throw new SPException(string.Format("Unable to update field properties. Is the list \"{0}\" valid and/or accessible?" , ausList.AssetUrl ) , ie);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        #endregion
    }
}
